﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;

namespace JoyeriaProject
{
    public partial class frmCustomerFinder : Form
    { 
        private IFormatProvider culture = new CultureInfo("en-US", true);
        private frmMain.ExplorerFormReturn ReturnedValues;
        private ModeloDatos MD = new ModeloDatos();
        private DataTable DTpagos;
        private DataTable DTcompras;

        public frmCustomerFinder(frmMain.ExplorerFormReturn del)
        {
            ReturnedValues = del;
            InitializeComponent();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Dispose();
        }

        private void clearAlltxt()
        {
            lblFolioNum.Text   = "";
            txtNombre.Text =   "";
            txtApellidos.Text   = "";
            txtTipoPago.Text   = "";
            txtTel.Text =   "";
            txtCel.Text =   ""; 
            txtDiaCobro.Text = "";
            txtAgent.Text = "";
            txtRuta.Text = "";
            dataGridView.DataSource = "";
            dataGridCompras.DataSource = "";
            lblCargos.Text = "INFO_COMPRAS";
            lblCargos.ForeColor = Color.White;
            lblInfoPagos.Text = "INFO_PAGOS";
            lblInfoPagos.ForeColor = Color.White;
            lblInfoPagos.BackColor = Color.Transparent;
            lblBalance.Text = "0.0";
            txtFind.Text = "";
            btnPago.Enabled = false;
            btnEdit.Enabled = false;
            btnPrint.Enabled = false;
            btnCompras.Enabled = false;
            Confiabilidad.BackColor = Color.Transparent;
          //  CUSTOMER_ID = 0;
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            LoadInfo();
        }

        private void frmCustomerFinder_Load(object sender, EventArgs e)
        {
            txtFind.Focus();
        }

        private void txtApellidos_TextChanged(object sender, EventArgs e)
        {

        }

        private void LoadInfo(int flag = 0)
        {
            if (txtFind.Text != string.Empty) 
            {
                IFormatProvider culture = new CultureInfo("en-US", true);
                
                try
                {
                    MD.Client = MD.GetClients().First
                       (
                           n =>
                           n.Nombre.ToUpper().Contains(txtFind.Text.ToUpper()) ||
                           n.Apellidos.ToUpper().Contains(txtFind.Text.ToUpper()) ||
                           n.CustomerID.ToString().Contains(txtFind.Text)
                         );
 
                    lblFolioNum.Text = MD.Client.CustomerID.ToString();
                    txtNombre.Text = MD.Client.Nombre;
                    txtApellidos.Text = MD.Client.Apellidos;
                    txtTipoPago.Text = "$" + MD.Client.MontoAbono + " PESOS " + (MD.Client.TipoAbono == 1 ? "DIARIO" : (MD.Client.TipoAbono == 7) ? "SEMANAL" : (MD.Client.TipoAbono == 14) ? "CATORCENAL" : (MD.Client.TipoAbono == 15) ? "QUINCENAL" : (MD.Client.TipoAbono == 30) ? "MENSUAL" : (MD.Client.TipoAbono == 60) ? "BIMESTRAL" : (MD.Client.TipoAbono == 90) ? "TRIMESTRAL" : (MD.Client.TipoAbono == 180) ? "SEMESTRAL" : "ANUAL");//results[3];
                    txtTel.Text = MD.Client.Telefono;
                    txtCel.Text = MD.Client.Celular;
                    txtAgent.Text = MD.Client.Agente;
                    txtRuta.Text = MD.Client.Ruta;
                    txtDiaCobro.Text = (MD.Client.DiaCobro.Equals(0) ? "DOMINGO" : MD.Client.DiaCobro.Equals(1) ? "LUNES" : MD.Client.DiaCobro.Equals(2) ? "MARTES" : MD.Client.DiaCobro.Equals(3) ? "MIERCOLES" : MD.Client.DiaCobro.Equals(4) ? "JUEVES" : MD.Client.DiaCobro.Equals(5) ? "VIERNES" : MD.Client.DiaCobro.Equals(6) ? "SABADO" : "");

                    List<ComprasPagos> comprasYpagos = (from n in MD.GetComprasPagos()
                                                        where (n.CustomerID == (int)MD.Client.CustomerID)
                                                        orderby n.Date
                                                        select n).ToList();

                    btnEdit.Enabled = true;
                    btnPago.Enabled = true;
                    btnCompras.Enabled = true;

                    if (comprasYpagos.Count > 0)
                    {
                        //////////////////////PAGOS///////////////////////////////////////////////

                        BindingSource bSource = new BindingSource();
                        double Saldos = 0;
                        DTpagos = new DataTable();

                        DTpagos.Columns.Add("ID");
                        DTpagos.Columns.Add("No");
                        DTpagos.Columns.Add("Fecha");
                        DTpagos.Columns.Add("Abono");
                        DTpagos.Columns.Add("Saldo");
                        DTpagos.Columns.Add("Firma");

                        foreach (var element in comprasYpagos)
                        {
                            Saldos = (Saldos + element.Cargo) - element.Abono;

                            if (element.Cargo == 0)
                            {
                                DataRow row = DTpagos.NewRow();

                                row["ID"] = element.ID;
                                row["No"] = element.CustomerID;
                                row["Fecha"] = element.Date.Day.ToString("00") + "/" + element.Date.Month.ToString("00") + "/" + element.Date.Year.ToString("0000");
                                row["Abono"] = element.Abono;
                                row["Saldo"] = Saldos;
                                row["Firma"] = element.Firma;
                                DTpagos.Rows.Add(row);
                                DTpagos.AcceptChanges();
                            }
                        }

                        bSource.DataSource = DTpagos;
                        if (flag.Equals(0))
                            this.dataGridView.DataSource = bSource;

                        
                        dataGridView.Columns["ID"].Visible = false;
                        dataGridView.Columns["No"].Visible = false;
                        dataGridView.Columns["Abono"].ReadOnly = false;
                        dataGridView.Columns["Fecha"].ReadOnly = false;
                        dataGridView.Columns["Saldo"].ReadOnly = true;
                        dataGridView.Columns["Firma"].ReadOnly = true;

                        dataGridView.Columns["Abono"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                        dataGridView.Columns["Fecha"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                        dataGridView.Columns["Saldo"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                        dataGridView.Columns["Firma"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;


                        /////////////////////////////////////////////////////////////////////////

                        //////////////////////COMPRAS///////////////////////////////////////////

                        BindingSource bSource2 = new BindingSource();

                        DTcompras = new DataTable();

                        DTcompras.Columns.Add("ID");
                        DTcompras.Columns.Add("No");
                        DTcompras.Columns.Add("Fecha");
                        DTcompras.Columns.Add("Articulo");
                        DTcompras.Columns.Add("Precio");
                        DTcompras.Columns.Add("Firma");

                        foreach (var element in comprasYpagos)
                        {
                            if (element.Cargo > 0)
                            {
                                DataRow row = DTcompras.NewRow();

                                row["ID"] = element.ID;
                                row["No"] = element.CustomerID;
                                row["Fecha"] = element.Date.Day.ToString("00") + "/" + element.Date.Month.ToString("00") + "/" + element.Date.Year.ToString("0000");
                                row["Articulo"] = element.Articulo;
                                row["Precio"] = element.Cargo;
                                row["Firma"] = element.Firma;
                                DTcompras.Rows.Add(row);
                                DTcompras.AcceptChanges();
                            }
                        }

                        bSource2.DataSource = DTcompras;
                        if (flag.Equals(0))
                            this.dataGridCompras.DataSource = bSource2;


                        dataGridCompras.Columns["ID"].Visible = false;
                        dataGridCompras.Columns["No"].Visible = false;
                        dataGridCompras.Columns["Fecha"].ReadOnly = false;
                        dataGridCompras.Columns["Articulo"].ReadOnly = true;
                        dataGridCompras.Columns["Precio"].ReadOnly = true;
                        dataGridCompras.Columns["Firma"].ReadOnly = true;

                        dataGridCompras.Columns["Articulo"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                        dataGridCompras.Columns["Fecha"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                        dataGridCompras.Columns["Precio"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                        dataGridCompras.Columns["Firma"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;


                        /////////////////////////////////////////////////////////////////////////

                        Confiabilidad.BackColor = (MD.VerificarStatus(Convert.ToInt32(lblFolioNum.Text)) == 0 ? Color.Green : Color.Red);
                      
                        lblBalance.Text = MD.GetSaldoCliente(Convert.ToInt32(lblFolioNum.Text)).ToString();
                        lblCargos.Text = comprasYpagos.Sum(n => n.Cargo).ToString();
                        
                        double HaceCuantoPago =0;
                        
                        try
                        {  
                            HaceCuantoPago = (DateTime.Now - MD.GetFechaUltimoPagoCliente(Convert.ToInt32(lblFolioNum.Text))).TotalDays;
                        }
                        catch (Exception ex)
                        {
                            lblInfoPagos.Text = "Este Cliente no ha realizado nunca un pago";
                            lblInfoPagos.ForeColor = Color.Red;
                            lblInfoPagos.BackColor = Color.White;
                            throw new Exception("NUNCA HA PAGADO");
                        }
                       
                        if (Convert.ToInt32(Math.Floor(HaceCuantoPago)) > MD.Client.TipoAbono)
                        {
                            //este pana no ha pagado a tiempo
                            lblInfoPagos.Text = (Convert.ToInt32(Math.Floor(HaceCuantoPago)) - MD.Client.TipoAbono).ToString() + " Dias sin pagar desde su ultimo dia de corte";
                            lblInfoPagos.ForeColor = Color.Red;
                            lblInfoPagos.BackColor = Color.White;
                        }
                        else
                        {
                            lblInfoPagos.Text = "Ultimo Pago Efectuado Hace " + Math.Floor(HaceCuantoPago).ToString() + " Dias";
                            lblInfoPagos.ForeColor = Color.Gold;
                            lblInfoPagos.BackColor = Color.Black;
                        }
                        btnPrint.Enabled = true;
                    }

             
                }
                catch (Exception ex)
                {
                    if(ex.Message != "NUNCA HA PAGADO")
                    {
                      clearAlltxt();
                      MessageBox.Show("NO ENCONTRADO", "LO SIENTO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
            }
         }
        
        private void btnPago_Click(object sender, EventArgs e)
        {
            frmPayment Pago = new frmPayment();
            Pago.CustomerID = Convert.ToInt32(lblFolioNum.Text);
            Pago.ShowDialog();
            txtFind.Text = Pago.CustomerID.ToString();
            LoadInfo();

        }

        private void btnCompras_Click(object sender, EventArgs e)
        {
            frmBuy Compra = new frmBuy();
            Compra.CustomerID = Convert.ToInt32(lblFolioNum.Text);
            Compra.ShowDialog();
            txtFind.Text = Compra.CustomerID.ToString();
            LoadInfo();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            //frmCustomerEdit EditCustomer = new frmCustomerEdit(ReturnedValues);
            //EditCustomer.CustomerID = Convert.ToInt32(lblFolioNum.Text);
            //EditCustomer.ShowDialog();
            //txtFind.Text = EditCustomer.CustomerID.ToString();
            ReturnedValues.Invoke("EDITCUSTOMER", Convert.ToInt32(this.lblFolioNum.Text));
        //    LoadInfo();
        }

        private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            DataRow tt = DTpagos.Rows[e.RowIndex];

            CustomSQL t = new CustomSQL
            {
                Insert = false,
                OrderBy = false,
                Select = false,
                Table = "Payments",
                Where = true,
                Update = true,
                KeyName = "ID",
                KeyValue = tt.ItemArray[0].ToString(),
            };   

            if (e.ColumnIndex == 2)
            {
                DateTime DateValidation;
                try
                { 
                    DateValidation = DateTime.ParseExact(tt.ItemArray[e.ColumnIndex].ToString(), "dd/MM/yyyy", culture);
                    t.Columns.Add(new SimpleDatabaseValues { parameter = "Fecha", value = tt.ItemArray[e.ColumnIndex].ToString().Substring(3, 2) + tt.ItemArray[e.ColumnIndex].ToString().Substring(0, 2) + tt.ItemArray[e.ColumnIndex].ToString().Substring(6, 4) });
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error en el Formato de la Fecha", "LO SIENTO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            else if (e.ColumnIndex == 3)
                t.Columns.Add(new SimpleDatabaseValues { parameter = "Abono", value = tt.ItemArray[e.ColumnIndex] });

            if ((bool)MD.CustomSQLTest(t))
                MessageBox.Show("Actualizado", "EXITO", MessageBoxButtons.OK, MessageBoxIcon.Information);
   
            LoadInfo(1);
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            //PrintManager PM = new PrintManager();

            MessageBox.Show("Espera La proxima Actualizacion!!", "SALUDOS", MessageBoxButtons.OK, MessageBoxIcon.Information);
   
        }

    }
}
